const path = require('path');
const { chromium } = require('playwright');
const Piscina = require('piscina');
const {
  login,
  getTaskLinks,
  chunk,
  browserArgs,
  getWorkerDayCount,
} = require('./utils');
const dayjs = require('dayjs');
const config = require('./config');

const piscina = new Piscina({
  minThreads: 2,
  maxThreads: 7,
  filename: path.resolve(__dirname, 'worker.js'),
});

(async () => {
  const browser = await chromium.launch({
    // headless: false,
    args: browserArgs,
  });

  const context = await browser.newContext();
  const page = await context.newPage();

  await login(page);

  const links = await getTaskLinks(page);
  const chunks = chunk(links, config.TASK_SIZE);
  const promises = [];

  for (const linkGroup of chunks) {
    promises.push(
      piscina.run({
        urls: linkGroup,
      })
    );
  }

  let data = [];
  const total = await Promise.all(promises).then((results) => {
    return results.reduce((acc, cur) => {
      data.push(...cur.data);
      return acc + cur.total;
    }, 0);
  });

  const details = data.reduce((acc, cur) => {
    const { title, hours } = cur;

    if (acc[title] === undefined) {
      return {
        ...acc,
        [title]: hours,
      };
    } else {
      return {
        ...acc,
        [title]: acc[title] + hours,
      };
    }
  }, {});

  const monthMessage = config.MATCH_MONTHS.map((m) =>
    dayjs(m).format('YYYY年MM月份')
  ).join('，');
  const workerDayCount = getWorkerDayCount(page);

  console.log(
    `🔥 ${monthMessage}，截止目前共${workerDayCount}个工作日，${
      workerDayCount * 8
    }个工时，禅道总工时${total}小时`
  );
  const keys = Object.keys(details);
  console.log(
    `✨ 项目总数：${keys.length}个，${
      keys.length > 0
        ? keys.map((v) => `${v}：${details[v]}小时`).join('，')
        : ''
    } `
  );

  await browser.close();
})();
